#!/usr/bin/env python

import json
from urllib import request

import datetime

from up_video.VideoSource import VideoSource

class DruidHotSource(VideoSource):

    def __init__(self) -> None:
        super().__init__()

    def get(self):
        data = '''
    {
      "queryType": "topN",
      "dataSource": "qizhu_crawl_video",
      "granularity": "all",
      "postAggregations": [
        {
          "fields": [
            {
              "fieldName": "max__playedNumber",
              "name": "max__playedNumber",
              "type": "fieldAccess"
            },
            {
              "fieldName": "min__playedNumber",
              "name": "min__playedNumber",
              "type": "fieldAccess"
            }
          ],
          "name": "delta__playedNumber",
          "fn": "-",
          "type": "arithmetic"
        },
        {
          "fields": [
            {
              "fields": [
                {
                  "fieldName": "max__playedNumber",
                  "name": "max__playedNumber",
                  "type": "fieldAccess"
                },
                {
                  "fieldName": "min__playedNumber",
                  "name": "min__playedNumber",
                  "type": "fieldAccess"
                }
              ],
              "name": "delta",
              "fn": "-",
              "type": "arithmetic"
            },
            {
              "fields": [
                {
                  "name": "max__playedNumber",
                  "type": "fieldAccess",
                  "fieldName": "max__playedNumber"
                },
                {
                  "value": 1000,
                  "type": "constant",
                  "name": "const"
                }
              ],
              "name": "plus",
              "fn": "+",
              "type": "arithmetic"
            }
          ],
          "name": "trend__playedNumber",
          "fn": "/",
          "type": "arithmetic"
        }
      ],
      "metric": "delta__playedNumber",
      "intervals": "%s+08:00/%s+08:00",
      "filter": {
        "fields": [
          {
            "field": {
              "fields": [
                {
                  "value": "\u56fd\u521b",
                  "type": "selector",
                  "dimension": "channel"
                },
                {
                  "value": "\u756a\u5267",
                  "type": "selector",
                  "dimension": "channel"
                }
              ],
              "type": "or"
            },
            "type": "not"
          },
          {
            "value": "bilibili",
            "type": "selector",
            "dimension": "site"
          }
        ],
        "type": "and"
      },
      "threshold": 250,
      "dimension": "itemLink",
      "aggregations": [
        {
          "type": "count",
          "name": "count"
        },
        {
          "fieldName": "playedNumber",
          "name": "min__playedNumber",
          "type": "longMin"
        },
        {
          "fieldName": "playedNumber",
          "name": "max__playedNumber",
          "type": "longMax"
        }
      ]
    }
    '''
        # 2018-08-22T21:20:28
        d = datetime.timedelta(days=7)
        data = data % ((datetime.datetime.now() - d).strftime("%Y-%m-%dT%H:%M:%S"),
                       datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S"))
        # print(data)
        req = request.Request('http://node19-67-195-bdyf.qiyi.hadoop:8082/druid/v2/?pretty')
        req.add_header('User-Agent',
                       'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
        req.add_header('Content-Type',
                       'application/json')

        with request.urlopen(req, data=data.encode('utf-8')) as f:
            print('Status:', f.status, f.reason)
            for k, v in f.getheaders():
                print('%s: %s' % (k, v))
            rsp = f.read().decode('utf-8')
            # print(json.loads(rsp)[0])
            result = [rs["itemLink"] for rs in json.loads(rsp)[0]["result"]]
            print(result)
            return result


if __name__ == '__main__':
    print(DruidHotSource().get())
